<?php

/**
 * @author ngockv@gmail.com
 * @copyright 2012
 */

function image_upload($image_name, $default=false, $file_name=''){
	if (($_FILES[$image_name] == "none") OR (empty($_FILES[$image_name]['name'])) ){
   return $default;
  }
  
  $dir = 'files/'.date('Ymd', time());
  file_check_dir($dir);
  
  $aName = explode('.', $_FILES[$image_name]['name']);
  $ext = array_pop($aName);	
	if (empty($file_name)){
		$file_name = implode('-', $aName);
	}
	
  $file_name = make_friendly_title($file_name, true);
	$path = image_path_unique($dir.'/'.$file_name.'.'.$ext);
  
  $url = PG_ROOT.$path;
  
 //extensive suitability check before doing anything with the file...
  if ($_FILES[$image_name]["size"] == 0){
		return $default;
  }else if (($_FILES[$image_name]["type"] != "image/pjpeg") AND ($_FILES[$image_name]["type"] != "image/jpeg") AND ($_FILES[$image_name]["type"] != "image/png")){
		return $default;
  }else if (!is_uploaded_file($_FILES[$image_name]["tmp_name"])){
		return $default;
  } else {
	  $move = @ move_uploaded_file($_FILES[$image_name]['tmp_name'], $url);
	  if(!$move){
	    return $default;
	  }
  }
  
  return $path;
}

function image_seo($image_path, $title){
	if (empty($title)) return false;
	if (!file_exists($image_path)) return false;
	
	$ext = array_pop(explode('.', $image_path));
	$title = make_friendly_title($title);
	
	$dir = 'files/'.date('Ymd', time());
  file_check_dir($dir);
	$path = image_path_unique($dir.'/'.$title.'.'.$ext);
	$res = @rename($image_path, $path);
	
	return $res?$path:false;
}

function image_path_unique($image_path){
	$aName = explode('.', $image_path);
	$ext = array_pop($aName);
	$imagePref = implode('.', $aName);
	
	$count = 0;
	while (file_exists($image_path)){
		$image_path = $imagePref.'-'.$count.'.'.$ext;
		$count++;
	}
	
	return $image_path;
}

function image_download($url, $file_name=''){
	$dir = 'files/'.date('Ymd', time());
  file_check_dir($dir);
  
  $ext = 'jpg';
  $aName = explode('/', $url);
	if (empty($file_name)){
		$file_name = array_pop($aName);
	}
	
  $file_name 	= make_friendly_title($file_name);
	$path				= $dir.'/'.$file_name.'-'.time().'.'.$ext;
  $imageUrl 	= PG_ROOT.$path;
  
	$ch = curl_init($url);
	$fp = fopen($imageUrl, 'wb');
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	if (strpos($url, 'https')===0){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	}	
	curl_exec($ch);
	curl_close($ch);
	fclose($fp);
	
	return $path;
}

function file_check_dir($dir){
  $path = PG_ROOT.$dir;
  if (!file_exists($path)){
  $aPath = explode('/', $dir); array_pop($aPath);
  file_check_dir(implode('/', $aPath));
  @mkdir($path); chmod($path, 0777);
  }
}

function image_thumb_settings(){
  return array(
   'crop140x140' => array(
		'type'  	=> 'crop',
		'width'   => 140,
		'height'  => 140
   ),
   
   'crop25x25' => array(
		'type'  	=> 'crop',
		'width'   => 25,
		'height'  => 25
   ),
   
   'crop124x124' => array(
		'type'  	=> 'crop',
		'width'   => 124,
		'height'  => 124
   ),
   
   'w210' => array(
		'type'  	=> 'scale',
		'width'   => 210
   ),
   
   'crop620x400' => array(
		'type'  	=> 'crop',
		'width'   => 620,
		'height'	=> 400
   ),
   
   'w105' => array(
		'type'  	=> 'scale',
		'width'   => 105
   ),
   
   'crop40x40' => array(
		'type'  	=> 'crop',
		'width'   => 40,
		'height'  => 40
   ),
   
   'crop100x100' => array(
		'type'  	=> 'crop',
		'width'   => 100,
		'height'  => 100
   ),
   
   'h75' => array(
		'type'  	=> 'scale',
		'height'  => 75
   ),
	);
}

function image_thumb($path, $thumb){
  $thumbSetting = image_thumb_settings();
  if (!isset($thumbSetting[$thumb])) return $path;
  
  $aPath = explode('/', $path);
  $files = array_shift($aPath);
  if ($files != 'files') return $path;
  
  return 'files/thumb/'.$thumb.'/'.implode('/', $aPath);
}

function imagealphamask( &$picture, $mask ) {
  // Get sizes and set up new picture
  $xSize = imagesx( $picture );
  $ySize = imagesy( $picture );
  $newPicture = imagecreatetruecolor( $xSize, $ySize );
  imagesavealpha( $newPicture, true );
  imagefill( $newPicture, 0, 0, imagecolorallocatealpha( $newPicture, 0, 0, 0, 127 ) );

  // Resize mask if necessary
  if( $xSize != imagesx( $mask ) || $ySize != imagesy( $mask ) ) {
    $tempPic = imagecreatetruecolor( $xSize, $ySize );
    imagecopyresampled( $tempPic, $mask, 0, 0, 0, 0, $xSize, $ySize, imagesx( $mask ), imagesy( $mask ) );
    imagedestroy( $mask );
    $mask = $tempPic;
  }

  // Perform pixel-based alpha map application
  for( $x = 0; $x < $xSize; $x++ ) {
    for ($y = 0; $y < $ySize; $y++) {
      $alpha = imagecolorsforindex($mask, imagecolorat($mask, $x, $y));
      $alpha = 127 - floor($alpha['red'] / 2);
      if (127 == $alpha) {
        continue;
      }
      $color = imagecolorsforindex($picture, imagecolorat($picture, $x, $y));
      imagesetpixel($newPicture, $x, $y, imagecolorallocatealpha(
      $newPicture, $color['red'], $color['green'], $color['blue'], $alpha));
    }
  }

  // Copy back to original picture
  imagedestroy( $picture );
  $picture = $newPicture;
}

?>